package com.tripspins.app.fragment;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.tripspins.app.R;
import com.tripspins.app.bo.Attachment;
import com.tripspins.app.bo.Pin;
import com.tripspins.app.bo.Trip;
import com.tripspins.app.helper.FILE_TYPE;
import com.tripspins.app.helper.MapsAPIHelper;
import com.tripspins.app.interfaces.OnFragmentInteractionListener;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLngBounds;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;

import java.util.ArrayList;
import java.util.HashMap;

public class MapDetailsPinFragment extends Fragment {
    private OnFragmentInteractionListener mListener;
    private Pin pin;
    private long tripId;
    private static final String ARG_PIN = "arg_pin";
    private static final String ARG_TRIP_ID = "arg_trip_id";
    TextView pinTitle;
    TextView pinNote;
    TextView pinDetails;
    ImageView pinWeatherIcon;
    TextView pinWeatherInfo;
    TextView pinAddressInfo;
    LinearLayout pinScrollAttachments;
    private SupportMapFragment mapFragment;
    private MapsAPIHelper mapsHelper;
    HashMap<String,Pin> markersMap;

    public static MapDetailsPinFragment newInstance(Pin pin, long tripId) {
        MapDetailsPinFragment fragment = new MapDetailsPinFragment();
        Bundle args = new Bundle();
        args.putParcelable(ARG_PIN, pin);
        args.putLong(ARG_TRIP_ID, tripId);
        fragment.setArguments(args);
        return fragment;
    }
    public MapDetailsPinFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            pin = getArguments().getParcelable(ARG_PIN);
            tripId = getArguments().getLong(ARG_TRIP_ID);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View viewRoot = inflater.inflate(R.layout.fragment_map_pin_details, container, false);
        mapFragment = SupportMapFragment.newInstance();
        FragmentManager fragmentManager = getChildFragmentManager();
        if(fragmentManager.getFragments() == null)
            fragmentManager.beginTransaction().add(R.id.map_details_holder,mapFragment).commit();

        loadViews(viewRoot);
        markersMap = new HashMap<String, Pin>();

        return viewRoot;
    }

    private void loadViews(View viewRoot) {
        pinTitle = (TextView)viewRoot.findViewById(R.id.map_title_pin);
        pinScrollAttachments = (LinearLayout)viewRoot.findViewById(R.id.map_attachments_list_pin);
        pinNote = (TextView)viewRoot.findViewById(R.id.map_note_pin);
        pinWeatherIcon = (ImageView)viewRoot.findViewById(R.id.map_weather_img_pin);
        pinWeatherInfo = (TextView)viewRoot.findViewById(R.id.map_weather_degrees_pin);
        pinAddressInfo = (TextView)viewRoot.findViewById(R.id.map_address_pin);
        pinDetails = (TextView)viewRoot.findViewById(R.id.map_text_details_pin);

        pinTitle.setText(pin.getTitle());
        pinNote.setText(pin.getTextNote());
        pinDetails.setText(pin.getDateFormatted());
        pinWeatherInfo.setText(String.valueOf(pin.getCurrentWeather().getTempC()) + "ºC");
        pinAddressInfo.setText(pin.getAddressString());
        pinWeatherIcon.setVisibility(View.VISIBLE);
        pinWeatherIcon.setImageURI(Uri.fromFile(pin.getWeatherIconUri(getActivity(), tripId)));

        loadTopMenu();
        loadAttachmentsThumbnails(pin);


    }

    @Override
    public void onResume() {
        super.onResume();
        if(mapFragment.getMap() != null) {
            MarkerOptions markerOptions = mapsHelper.getMarker(pin);
            Marker marker = mapFragment.getMap().addMarker(markerOptions);
            markersMap.put(marker.getId(), pin);


            mapFragment.getView().getViewTreeObserver().addOnGlobalLayoutListener(
                    new ViewTreeObserver.OnGlobalLayoutListener() {
                        @Override
                        public void onGlobalLayout() {
                            if(mapFragment.getMap() != null) {
                                CameraUpdate center = null;
                                LatLngBounds bound = new LatLngBounds(pin.getLatLng(), pin.getLatLng());
                                center = CameraUpdateFactory.newLatLngZoom(pin.getLatLng(), 12.0f);
                                mapFragment.getMap().moveCamera(center);
                            }
                        }
                    });
        }
    }

    private static class AuxParam
    {
        public Pin pin;
        public LinearLayout scroll;
        public Context context;
    }
    private void loadAttachmentsThumbnails(Pin pin) {

        pinScrollAttachments.removeAllViews();
        AuxParam param = new AuxParam();
        param.pin = pin;
        param.scroll = pinScrollAttachments;
        param.context = getActivity();

        new AsyncTask<AuxParam,Void, ArrayList<View>>()
        {
            AuxParam param;
            ArrayList<View> list;

            @Override
            protected ArrayList<View> doInBackground(AuxParam... params) {
                param = params[0];
                ImageView thumbnail;
                list = new ArrayList<View>();
                for(Attachment a : param.pin.getAttachments())
                {
                    //TODO incluir outros thumbnails
                    if(a.getFileType() == FILE_TYPE.IMAGE ||a.getFileType() == FILE_TYPE.VIDEO)
                    {
                        final Attachment att = a;
                        thumbnail = new ImageView(param.context);
                        thumbnail.setLayoutParams(new ViewGroup.LayoutParams(
                                ViewGroup.LayoutParams.WRAP_CONTENT,
                                ViewGroup.LayoutParams.MATCH_PARENT));
                        thumbnail.setScaleType(ImageView.ScaleType.FIT_START);
                        thumbnail.setPadding(0,3,3,0);
                        try {
                            thumbnail.setImageURI(Uri.parse(a.getThumbnailPath()));
                        }catch (Throwable e1){
                            System.gc();
                            try{
                                thumbnail.setImageURI(Uri.parse(a.getThumbnailPath()));

                            }catch (Throwable e2){
                                Log.e("TP",e2.getMessage());
                            }
                        }
                        thumbnail.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                Intent intent = new Intent();
                                intent.setAction(android.content.Intent.ACTION_VIEW);
                                if (att.getFileType() == FILE_TYPE.IMAGE )
                                    intent.setDataAndType(Uri.parse("file://" + att.getPath()), "image/*");
                                else intent.setDataAndType(Uri.parse("file://" + att.getPath()), "video/*");
                                getActivity().startActivity(intent);
                            }
                        });
                        list.add(thumbnail);
                    }

                }
                return list;
            }

            @Override
            protected void onPostExecute(ArrayList<View> views) {
                super.onPostExecute(views);
                for (View v : views)
                    pinScrollAttachments.addView(v);

            }
        }.execute(param);

    }



    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mListener = (OnFragmentInteractionListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }
    @Override
    public void onPrepareOptionsMenu(Menu menu) {
        super.onPrepareOptionsMenu(menu);
        menu.clear();
        loadTopMenu();
    }

    private void loadTopMenu() {
       getActivity().getActionBar().setCustomView(null);
    }
    public void onDestroyView() {
        super.onDestroyView();
    }
}
